﻿package com.reyco1.tool 
{
	/*
	imports
	*/
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.Event;
	import com.reyco1.events.RSSEvent;
	import com.reyco1.extension.DispatchExtension;
	/*
	class
	*/
	
	/**
	 * Based on the Adobe Flash CS3 Actionscript examples
	 * 
	 */	
	public class RSSParser extends DispatchExtension 
	{
		/*
		variables
		*/
		public var rssXML:XML;
		public var rssOutput:String;
		public var rssTitle:String;
		private var myLoader:URLLoader;
		/*
		constructor
		*/
		/**
		 * RSSParser constructor
		 * @param $url : path to the RSS feed
		 * 
		 */		
		public function RSSParser($url:String):void
		{
			var rssXMLURL:URLRequest = new URLRequest($url);
			this.myLoader = new URLLoader(rssXMLURL);
			this.myLoader.addEventListener("complete", this.xmlLoaded);
		}
		
		/*
		functions
		*/
		
		/**
		 * 
		 * @eventType com.reyco1.events.RSSEvent.PARSED
		 * 
		 */				
		private function xmlLoaded(evtObj:Event):void 
		{ 
			this.rssXML = XML(this.myLoader.data);
			
			//trace(rssXML)
			
			var outXML:XMLList = new XMLList();
			
			if (this.rssXML.namespace("") != undefined) {
				default xml namespace = this.rssXML.namespace("");
			}
			
			for each (var item:XML in this.rssXML..item) {
				var itemTitle:String = item.title.toString();
				var itemDescription:String = item.description.toString();
				var itemLink:String = item.link.toString();
				var itemDate:String = item.pubDate.substr(8, 3)+" "+item.pubDate.substr(5, 2);
				outXML += buildItemHTML(itemTitle, itemDate, itemDescription, itemLink);
			}
			
			XML.prettyPrinting = false;
			this.rssOutput = outXML.toXMLString();
			this.rssTitle = rssXML.channel.title.toString();
			
			this.dispatchEvent(new RSSEvent(RSSEvent.PARSED, {}));
		}
		
		private function buildItemHTML(itemTitle:String, itemDate:String, itemDescription:String, itemLink:String):XMLList 
		{
			default xml namespace = new Namespace();
			var body:XMLList = new XMLList();
			
			body += new XML("<b>" + itemTitle + "</b>");
			body.appendChild(<br/>);
			
			var time:XML = new XML("<p>-- " + itemDate + " --</p>")
			body += time;
			
			var p:XML = new XML("<p>" + itemDescription + "</p>");
			
			var link:XML = <a></a>;
			link.@href = itemLink;
			link.font.@color = "#0000ff";
			link.font = "Read more...";
			
			p.appendChild(<br/>);
			p.appendChild(link); 
			body += p;
			
			return body;
		}	
	}
}